#!/usr/bin/env python

from models import *
import random
from google.appengine.ext import db
from django.utils import simplejson as json


def new_task(inputs_str, script):
  inputs = []
  to_put = []
  for prompt in inputs_str.split('\r\n'):
    item = WorkItem(prompt=prompt)
    to_put.append(item)
  todo = db.put(to_put)
  task = Task(script=script, todo=todo, random=random.random())
  db.put(task)

def accept_answer(body):
  data = json.loads(body)
  task = db.get(data['taskKey'])
  to_put = [task]
  items = data['items']

  user_id = data['user']
  user = None
  if len(user_id) > 0:
    user = AppUser.get_by_key_name(user_id)
    user.items_completed += len(items)
    to_put.append(user)

  for i in items:
    item = db.get(i['itemKey'])
    try:
      task.todo.remove(item.key())
    except ValueError:
      pass
    if item.key() not in task.done:
      task.done.append(item.key())
      item.result = str(i['answer'])
      to_put.append(item)
  if not task.todo:
    task.random = -1.0
  db.put(to_put)